package pl.mw.cmd.internal.telnetserver;

import org.jboss.netty.channel.Channel;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;

import pl.mw.cmd.greeting.Greeting;
import pl.mw.cmd.telnetserver.MessageReceiver;
import pl.mw.cmd.telnetserver.ReplaySender;

/**
 * Serwer telnet.
 */
public class TelnetServer extends BaseTelnetServer {
	
	/** Odpowiada za odbior komunikatow */
	private ServiceReference receiver;
	
	/** Kontekst komponentu. */
	private ComponentContext ctx;

	
	/**
	 * Tworzy komponent serwera telnet.
	 */
	public TelnetServer() {
		System.out.println("[pl.mw.cmd.telnetserver] [TelnetServer] Component created.");
	}
	
	/**
	 * Ustawia interpreter komend.
	 * @param commandInterpreter interpreter komend
	 */
	public void setReceiver(ServiceReference receiver) {
		this.receiver = receiver;
		
		System.out.println("[pl.mw.cmd.telnetserver] [TelnetServer] receiver bound.");
	}
	
	/**
	 * Wylacza ssinterpreter komend.
	 * @param commandInterpreter interpreter komend
	 */
	public void unsetReceiver(ServiceReference receiver) {
		this.receiver = null;
		
		System.out.println("[pl.mw.cmd.telnetserver] [TelnetServer] receiver unbound.");
	}
	
	/**
	 * Startuje serwer telnet.
	 */
	public void start(ComponentContext pCtx) {
		super.start();
		this.ctx = pCtx;
		System.out.println("[pl.mw.cmd.telnetserver] [TelnetServer] Component activated.");
	}

	
	/**
	 * Zatrzymuje serwer telnet.
	 */
	public void stop() {
		super.stop();
		System.out.println("[pl.mw.cmd.telnetserver] [TelnetServer] Component deactivated.");
	}
	
	/**
	 * {@inheritDoc}
	 * 
	 * @see BaseTelnetServer#channelConnected(Channel)
	 */
	@Override
	protected void channelConnected(ReplaySender replaySender) {
		String msg = Greeting.getGreetingMessage();
		replaySender.send(msg + "\r\n> ");
	}
	
	/**
	 * {@inheritDoc}
	 * 
	 * @see BaseTelnetServer#messageReceived(String, Channel)
	 */
	@Override
	protected void messageReceived(String message, ReplaySender replaySender) {
		if (message.trim().toLowerCase().equals("bye")) {
			replaySender.send("Do zobaczenia.\r\n");
			replaySender.close();
		} else if (this.receiver == null) {
			replaySender.send("Interpreter polecen nie jest dostepny.\r\n> ");
		} else {
			getReceiver().messageReceived(message, replaySender);
		} 
	}
	
	/**
	 * Pobiera obiekt {@link MessageReceiver}
	 * @return obiekt {@link MessageReceiver}
	 */
	public MessageReceiver getReceiver() {
		return (MessageReceiver) this.ctx.locateService("MessageReceiver", this.receiver);
	}

}
